<template>
  <div class="main">
    <div class="topTitle">{{title}}</div>
    <div class="form_content">
      <NScrollbar>
        <NSpin
          :show="spinShow"
        >
          <div class="content">
            <NForm
              ref="formRef"
              :rules="rules"
              :model="formValue"
              require-mark-placement="left"
              label-placement="left"
              :label-width="140"
              style="width: 1000rem"
              label-align="right"
            >
              <NSpace>
                <NFormItem
                  label="名称:"
                  path="scheduleName"
                >
                  <NInput
                    placeholder="请输入名称"
                    v-model:value="formValue.scheduleName"
                    clearable
                    class="commonWidth"
                  />
                </NFormItem>
              </NSpace>
              <NSpace>
                <NFormItem
                  label="签到时间:"
                  path="startScheduleDate"
                  ref="startScheduleDate"
                >
                  <NTimePicker
                    v-model:formatted-value="formValue.startScheduleDate"
                    value-format="HH:mm:ss"
                    class="commonWidth"
                    @update:value="updateStartScheduleDate"
                  />
                </NFormItem>
              </NSpace>
              <NSpace>
                <NFormItem
                  label="签出时间:"
                  path="endScheduleDate"
                  ref="endScheduleDate"
                >
                  <NTimePicker
                    v-model:formatted-value="formValue.endScheduleDate"
                    value-format="HH:mm:ss"
                    class="commonWidth"
                    @update:value="updateEndScheduleDate"
                  />
                </NFormItem>
              </NSpace>
              <NSpace>
                <NFormItem
                  label="服务类型:"
                  path="serviceTypeCode"
                >
                  <NSelect
                    :options="serviceTypeOption"
                    v-model:value="formValue.serviceTypeCode"
                    placeholder="请选择服务类型"
                    clearable
                    class="commonWidth"
                    @update-value="changeRelVolunteer"
                  />
                </NFormItem>
              </NSpace>
              <NSpace>
                <NFormItem
                  label="文润志愿服务联盟:"
                  path="leagueId"
                >
                  <NSelect
                    :options="listOption"
                    v-model:value="formValue.leagueId"
                    placeholder="请选择联盟"
                    clearable
                    class="commonWidth"
                    @update-value="changeRelVolunteers"
                  />
                </NFormItem>
              </NSpace>
              <NSpace>
                <NFormItem
                  label="执行人:"
                  path="volunteer"
                >
                  <NCheckboxGroup
                    v-model:value="volunteers"
                    @update:value="handleCheckedChange()"
                  >
                    <NSpace>
                      <!-- <NCheckbox
                        v-for="item in relVolunteerList"
                        :key="item.id"
                        :value="item.id"
                        :label="item.name"
                      /> -->
                      <NCheckbox
                        v-for="item in relVolunteerList"
                        :key="item.id"
                        :value="item.id"
                        :label="item.name"
                      />
                    </NSpace>
                  </NCheckboxGroup>
                </NFormItem>
              </NSpace>
              
              <NSpace>
                <NFormItem
                  label="备注:"
                  path="remark"
                >
                  <NInput
                    type="textarea"
                    placeholder="请输入备注"
                    v-model:value="formValue.remark"
                    clearable
                    class="commonWidth"
                  />
                </NFormItem>
              </NSpace>
            </NForm>
          </div>
        </NSpin>
      </NScrollbar>
    </div>
  </div>
  <FixedAction>
    <NSpace justify="center">
      <NSpace justify="start" style="flex: 0 0 42%">
        <NButton style="width: 78px; color: #5fb17f" ghost @click="goBack">
          返回
        </NButton>
      </NSpace>

      <NSpace justify="center">
        <NButton type="primary" style="width: 78px" @click="confirm()" :loading="loading">
          保存
        </NButton>
      </NSpace>

      <NSpace justify="end" style="flex: 0 0 42%" v-if="route.params.id">
        <NButton type="error" style="width: 78px"  @click="remove()">
          删除
        </NButton>
      </NSpace>
    </NSpace>
  </FixedAction>
  <NModal :auto-focus="false" v-model:show="modalVisible">
    <VDialogContent
      @close="modalVisible = false"
      @submit="againDelete"
      title="删除提示"
    >
      <div style="width: 300rem; height: 100rem; text-align: center; line-height: 100rem">
        您确定要删除吗?
      </div>
    </VDialogContent>
  </NModal>
</template>
<script setup lang="ts">
import { ref, reactive, watch, onMounted } from 'vue'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'
import {
  NSpace,
  NSelect,
  NForm,
  NInput,
  NFormItem,
  NButton,
  NScrollbar,
  NDatePicker,
  NSpin,
  useMessage,
  NCheckboxGroup,
  NCheckbox,
  NTimePicker,
  NModal,
  FormItemInst
} from 'naive-ui'
import router from '@/router'
import { useTagStore } from '@/stores/layout'
import FixedAction from '@/components/FixedAction.vue'
import { sendRequest } from '@/utils/api'
import { useRoute } from 'vue-router'
import dayjs from 'dayjs';
const startScheduleDate = ref<FormItemInst | null>(null)
const endScheduleDate = ref<FormItemInst | null>(null)
const tags = useTagStore().tags
const message = useMessage()
const route = useRoute()
const title = ref('');
const id = ref<any>('');
const range = ref(null)
const scheduleDay = ref('');
onMounted(()=>{
  getServiceFunction();
  getFunction();
})

const Volunteers = ref({});

const spinShow = ref(false);

const modalVisible = ref(false);

function useQueryForm<T = unknown>(form: T, reset: Reset): [form: T, reset: Reset] {
  return [form, reset]
}

const [formValue, resetForm] = useQueryForm(
  reactive({
    endScheduleDate: null,
    id: null,
    leagueId: null,
    remark: null,
    scheduleName: null,
    serviceType: null,
    serviceTypeCode: null,
    startScheduleDate: null,
    volunteers: []
  }),
  () => {
    formValue.endScheduleDate = null
    formValue.id = null
    formValue.leagueId = null
    formValue.remark = null
    formValue.scheduleName = null
    formValue.serviceType = null
    formValue.serviceTypeCode = null
    formValue.startScheduleDate = null
    formValue.volunteers = []
  }
)

const defalutServiceTypeCode = ref('');
const defalutLeagueId = ref('');

const volunteers = ref([]);

const rules = {
  volunteers: {},
  serviceTypeCode: {
    required: true,
    trigger: ['change', 'blur'],
    message: '选择服务类型'
  },
  leagueId: {
    required: true,
    trigger: ['change', 'blur'],
    message: '选择文润志愿服务联盟'
  },
  volunteer: {
    required: true,
    trigger: ['change', 'blur'],
    validator(rule:any, value:any) {
      if (volunteers.value.length == 0) {
        return new Error('请选择执行人')
      }
      return true
    }
  },
  scheduleName: {
    required: true,
    trigger: ['input'],
    validator(rule:any, value:any) {
      if (!value) {
        return new Error('请填写名称')
      }
      if (value.length > 100) {
        return new Error('名称字数不得超过100字')
      }
      return true
    }
  },
  endScheduleDate: {
    required: true,
    trigger: ['change', 'blur', 'end_Date'],
    validator(rule:any, value:any) {
      if (!value) {
        return new Error('请选择签出时间')
      }
      else {
        if (formValue.startScheduleDate) {
          let start = dayjs(`${scheduleDay.value} ${formValue.startScheduleDate}`)
          let end = dayjs(`${scheduleDay.value} ${value}`)
          if (end.diff(start, 'second') < 0) {
            return new Error('签出时间不能早于签到时间')
          } else {
            return true
          }
        } else {
          return true
        }
      }
    }
  },
  startScheduleDate: {
    required: true,
    trigger: ['change', 'blur', 'start_Date'],
    validator(rule:any, value:any) {
      if (!value) {
        return new Error('请选择签到时间')
      } else {
        if (formValue.endScheduleDate) {
          let start = dayjs(`${scheduleDay.value} ${value}`)
          let end = dayjs(`${scheduleDay.value} ${formValue.endScheduleDate}`)
          if (end.diff(start, 'second') < 0) {
            return new Error('签到时间不能晚于签出时间')
          } else {
            return true
          }
        } else {
          return true
        }
      }
    }
  },
}

const updateStartScheduleDate = () => {
  if (formValue.endScheduleDate) {
    setTimeout(()=>{
      startScheduleDate.value?.validate({ trigger: 'start_Date' })
      endScheduleDate.value?.validate({ trigger: 'end_Date' })
    }, 200)
  }
}

const updateEndScheduleDate = async() => {
  if (formValue.startScheduleDate) {
    setTimeout(()=>{
      startScheduleDate.value?.validate({ trigger: 'start_Date' })
      endScheduleDate.value?.validate({ trigger: 'end_Date' })
    }, 200)
  }
}

const serviceTypeOption = ref([]);
const listOption = ref([]);
const relVolunteerList = ref([]);

const handleCheckedChange = () => {
  // console.log('relVolunteerList', relVolunteerList.value);
  // console.log('volunteers', volunteers.value);
}

const realVolunteerList = ref([]);

const getInfo = async() => {
  let id = route.params.id;
  // console.log('route', route)
  const [error, res] = await sendRequest<HttpResponsePagination<any>>({
    module: 'volunteer',
    api: 'volunteerScheduleInfo',
    uri: {
      id: id
    }
  })
  if (error) throw new Error(error.message)
  if (res.code !== 0) throw new Error(res.msg)
  if (res.code == 0) {
    scheduleDay.value = res.data.startScheduleDate.split(' ')[0];
    res.data.startScheduleDate = dayjs(res.data.startScheduleDate).format('HH:mm:ss');
    res.data.endScheduleDate = dayjs(res.data.endScheduleDate).format('HH:mm:ss')
    Object.assign(formValue, res.data);
    onLoadRelVolunteer(false);
    if (res.data.volunteers && res.data.volunteers.length > 0) {
      res.data.volunteers.forEach((item:any)=>{
        volunteers.value.push(item.volunteerId)
      })
      // console.log('volunteers.value1', res.data.volunteers)
      // console.log('volunteers.value', volunteers.value)
      realVolunteerList.value = res.data.volunteers;
    }
  }
}

const onLoadRelVolunteer = async(flag:boolean) => {
  // console.log('flag', flag)
  if (formValue.leagueId && formValue.serviceTypeCode) {
    // if (flag) {
    //   relVolunteerList.value = [];
    // }
    if (flag) {
      volunteers.value =[];
    }
    const [error, res] = await sendRequest<HttpResponse>({
      module: 'volunteer',
      api: 'volunteerLeagueRelVolunteer',
      override: {
        params: {
          leagueId: formValue.leagueId,
          serviceTypeCode: formValue.serviceTypeCode,
        }
      }
    })
    if (error) return message.error(error.message)
    let dataList:any = {...Volunteers.value};
    let key = `${formValue.leagueId}-${formValue.serviceTypeCode}`;
    dataList[key] = res.data;
    Volunteers.value = dataList;
    relVolunteerList.value = res.data;
  }
}

//下拉
const getFunction = async () => {
  listOption.value = []
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'volunteer',
    api: 'leagueOptions'
  })
  if (error) return message.error(error.message)
  res.data.forEach((i: any) => {
    // @ts-ignore
    listOption.value.push({ label: i.label, value: i.value })
  })
  if (!route.params.id) {
    formValue.leagueId = res.data[0].value;
    defalutLeagueId.value = res.data[0].value;
  }
}

const getServiceFunction = async () => {
  serviceTypeOption.value = []
  const [error, res] = await sendRequest<HttpResponse>({
    module: 'clue',
    api: 'listByParentCode',
    override: {
      params: {
        dicCode: 'A56'
      }
    }
  })
  if (error) return message.error(error.message)
  res.data.forEach((i: any) => {
    // @ts-ignore
    serviceTypeOption.value.push({ label: i.dicName, value: i.dicCode })
  });
  if (!route.params.id) {
    formValue.serviceType = res.data[0].dicName;
    formValue.serviceTypeCode = res.data[0].dicCode;
    defalutServiceTypeCode.value = res.data[0].dicCode;
  }
}

// 返回
const goBack = () => {
  const index = tags.findIndex((item: any) => item.path === route.path)
  tags.splice(index, 1);
  modalVisible.value = false;
  if (tags.length == 0) {
    router.push({ name: 'VolunteerWorkSchedule' })
  } else history.back()
}

// 确定
const loading = ref(false)
const formRef = ref<FormInst | null>(null)
const confirm = () => {
  let list:any = [];
  relVolunteerList.value.forEach((item:any)=>{
    if (volunteers.value.indexOf(item.id) != -1) {
      list.push({
        volunteerId: item.id,
        volunteerName: item.name,
      })
    }
  })
  let params = {...formValue};
  params.volunteers = list;
  params.startScheduleDate = `${scheduleDay.value} ${params.startScheduleDate}`;
  params.endScheduleDate = `${scheduleDay.value} ${params.endScheduleDate}`;
  if (route.params.id) {
    formRef.value?.validate(async (error:any) => {
      if (error) return
      try {
        const [error, data] = await sendRequest({
          module: 'volunteer',
          api: 'volunteerScheduleUpdate',
          override: {
            data: params
          }
        })

        if (error) throw new Error(error.message)
        if (data.code !== 0) throw new Error(data.msg)
        message.success('操作成功')
        goBack()
      } catch (error: any) {
        message.error(error.message)
      }
    })
  } else {
    formRef.value?.validate(async (error) => {
      if (error) return
      try {
        delete params.id
        const [error, data] = await sendRequest({
          module: 'volunteer',
          api: 'volunteerScheduleSave',
          override: {
            data: params
          }
        });
        if (error) throw new Error(error.message)
        if (data.code !== 0) throw new Error(data.msg)
        message.success('操作成功');
        goBack()
      } catch (error: any) {
        message.error(error.message)
      }
    })
  }
}

const changeRelVolunteer = () => {
  // onLoadRelVolunteer(true);
}

const changeRelVolunteers = () => {
  // onLoadRelVolunteer(true);
}

const againDelete = async() => {
  const [error, data] = await sendRequest({
    module: 'volunteer',
    api: 'volunteerScheduleDel',
    override: {
      data: [route.params.id]
    }
  });
  if (error) throw new Error(error.message)
  if (data.code !== 0) {
    message.error(data.msg)
  } else {
    message.success('操作成功')
    goBack()
  }
}

const remove = () => {
  modalVisible.value = true;
}

watch([() => formValue.serviceTypeCode, () => formValue.leagueId], (newValues, oldValues) => {
  // console.log(`Name: ${newValues[0]}, Age: ${newValues[1]}`);
  // console.log(`Name1: ${oldValues[0]}, Age1: ${oldValues[1]}`);
  if (newValues[0]) {
    serviceTypeOption.value.forEach((item:any)=>{
      if (item.value == formValue.serviceTypeCode) {
        formValue.serviceType = item.label;
      }
    })
  }
  if(newValues[0] && newValues[1]) {
    if (newValues[0]!=oldValues[0] || newValues[1]!=oldValues[1]) {
      onLoadRelVolunteer(true);
    } else {
      onLoadRelVolunteer(false);
    }
  }
});

// watch(
//   () => formValue,
//   () => {
//     if (formValue.serviceTypeCode && formValue.leagueId) {
//       onLoadRelVolunteer();
//     }
//   },
//   { deep: true, immediate: true }
// )
onMounted(()=>{
  if (route.name == 'VolunteerWorkScheduleEdit') {
    title.value = '志愿者排班编辑';
    getInfo();
  } else {
    let schedule = route.query.scheduleDay;
    scheduleDay.value = schedule;
    title.value = '志愿者排班新建';
    resetForm();
  }
})

watch(
  () => route,
  () => {
    if (route.name == 'VolunteerWorkScheduleAdd') {
      let schedule = route.query.scheduleDay;
      scheduleDay.value = schedule;
      title.value = '志愿者排班新建';
      resetForm();
    }
    if (route.name == 'VolunteerWorkScheduleEdit') {
      title.value = '志愿者排班编辑';
      getInfo();
    }
  },
  { deep: true, immediate: true }
)
</script>

<style scoped lang="scss">
@mixin CommonFont {
  font-size: 16rem;
  font-family: PingFangSC, PingFang SC;
  font-weight: 400;
  color: rgba(0, 0, 0, 0.85);
}

.commonWidth {
  width: 360rem;
}

.main {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  overflow: hidden;

  .topTitle {
    width: 100%;
    height: 64rem;
    border-bottom: 1px solid #fff;
    padding: 20rem;
    margin-bottom: 20rem;
    @include CommonFont;
  }

  .form_content {
    width: 100%;
    height: 100%;
    padding: 0 20rem 0rem;

    .content {
      display: flex;
      align-items: center;
      flex-direction: column;
      width: 100%;
      height: 100%;
      padding: 20rem 0 180rem;
      overflow-y: scroll;
      background-color: #ebeceb;

      .scope {
        display: flex;
        flex-wrap: wrap;
        width: 100%;
        height: 130rem;
        background: #e1e1e1;
        padding: 15rem 20rem;

        .userBox {
          display: flex;
          justify-content: space-between;
          align-items: center;
          width: auto;
          min-width: 150rem;
          height: 40rem;
          background-color: #fff;
          border-radius: 4rem;
          padding: 0 10rem;
          margin-right: 20rem;
        }
      }
    }
  }
}

.iconStyle {
  margin-right: 5rem;
  color: #5fb17f;
}

.progress {
  width: 100%;
  min-height: 50rem;
  background-color: #d5e2d8;
  border-radius: 5rem;
  padding: 10rem;
  display: flex;
  align-items: center;
  margin-top: 10rem;
}

.content::-webkit-scrollbar {
  display: none;
}

:deep(.n-spin-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-scrollbar-container) {
  width: 100%;
  height: 100%;
}

:deep(.n-scrollbar-content) {
  width: 100%;
  height: 100%;
}

:deep(.n-spin-content) {
  width: 100%;
  height: 100%;
}
</style>
